package models

import (
	"gorm.io/gorm"
	"time"
	"user-srv/basic/inits"
	__ "user-srv/basic/proto"
)

// 会员等级表
type MemberLevel struct {
	Id        uint64         `gorm:"column:id;type:bigint UNSIGNED;primaryKey;not null;" json:"id"`
	BenefitId uint64         `gorm:"column:benefit_id;type:bigint UNSIGNED;comment:会员权益id;not null;" json:"benefit_id"` // 会员权益id
	Name      string         `gorm:"column:name;type:varchar(255);comment:会员名称;not null;" json:"name"`                  // 会员名称
	Price     float64        `gorm:"column:price;type:decimal(10, 2);comment:会员价格;not null;" json:"price"`              // 会员价格
	Level     int32          `gorm:"column:level;type:int;comment:会员等级;not null;" json:"level"`                         // 会员等级
	Desc      string         `gorm:"column:desc;type:varchar(255);comment:描述;not null;" json:"desc"`                    // 描述
	CreatedAt time.Time      `gorm:"column:created_at;type:datetime(3);not null;default:CURRENT_TIMESTAMP(3);" json:"created_at"`
	UpdatedAt time.Time      `gorm:"column:updated_at;type:datetime(3);not null;default:CURRENT_TIMESTAMP(3);" json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:datetime(3);default:NULL;" json:"deleted_at"`
}

// 会员等级表
func (ml *MemberLevel) TableName() string {
	return "member_level"
}

// 会员等级添加
func (ml *MemberLevel) MemberLevelAdd() error {
	return inits.DB.Create(&ml).Error
}

// 会员等级列表
func (ml *MemberLevel) MemberLevelFind(page, pageSize int) (MemberLevelFind []*__.MemberLevelFind, err error) {
	err = inits.DB.Model(&MemberLevel{}).Scopes(Paginate(page, pageSize)).Find(&MemberLevelFind).Error
	return
}

// 分页
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

// Level查询等级信息
func (ml *MemberLevel) MemberLevelFindByLevel() error {
	return inits.DB.Model(&ml).Where("level = ?", ml.Level).Limit(1).Find(&ml).Error
}

// Id查询等级信息
func (ml *MemberLevel) MemberLevelFindById(Id int) error {
	return inits.DB.Where("id = ?", Id).Limit(1).Find(&ml).Error
}

// 会员等级删除
func (ml *MemberLevel) MemberLevelDel() error {
	return inits.DB.Where("id = ?", ml.Id).Delete(&ml).Error
}
